/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.aabte.lota.auth.auth.shiro.configure;

import com.aabte.lota.auth.auth.shiro.CustomerModularRealmAuthenticator;
import com.aabte.lota.auth.auth.shiro.CustomerModularRealmAuthorizer;
import com.aabte.lota.auth.auth.shiro.StatelessDefaultSubjectFactory;
import com.aabte.lota.auth.auth.shiro.configure.exception.NoRealmBeanConfiguredException;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.config.Ini;
import org.apache.shiro.event.EventBus;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.mgt.SubjectDAO;
import org.apache.shiro.mgt.SubjectFactory;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.SimpleSessionFactory;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/** @since 1.4.0 */
@Configuration
@SuppressWarnings("SpringFacetCodeInspection")
@ConditionalOnProperty(name = "shiro.enabled", matchIfMissing = true)
public class ShiroAutoConfiguration {

  @Autowired(required = false)
  protected CacheManager cacheManager;

  @Autowired(required = false)
  protected RolePermissionResolver rolePermissionResolver;

  @Autowired(required = false)
  protected PermissionResolver permissionResolver;

  @Autowired protected EventBus eventBus;

  @Autowired protected List<Realm> realms;

  @Value("#{ @environment['shiro.sessionManager.deleteInvalidSessions'] ?: true }")
  protected boolean sessionManagerDeleteInvalidSessions;

  @Bean
  @ConditionalOnMissingBean
  protected AuthenticationStrategy authenticationStrategy() {
    return new AtLeastOneSuccessfulStrategy();
  }

  @Bean
  @ConditionalOnMissingBean
  protected Authenticator authenticator() {
    ModularRealmAuthenticator authenticator = new CustomerModularRealmAuthenticator();
    authenticator.setRealms(realms);
    authenticator.setAuthenticationStrategy(authenticationStrategy());
    return authenticator;
  }

  @Bean
  @ConditionalOnMissingBean
  protected Authorizer authorizer() {
    ModularRealmAuthorizer authorizer = new CustomerModularRealmAuthorizer();
    authorizer.setRealms(realms);

    if (permissionResolver != null) {
      authorizer.setPermissionResolver(permissionResolver);
    }

    if (rolePermissionResolver != null) {
      authorizer.setRolePermissionResolver(rolePermissionResolver);
    }

    return authorizer;
  }

  @Bean
  @ConditionalOnMissingBean
  protected SubjectDAO subjectDAO() {
    DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
    subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator());
    return subjectDAO;
  }

  @Bean
  @ConditionalOnMissingBean
  protected SessionStorageEvaluator sessionStorageEvaluator() {
    DefaultSessionStorageEvaluator evaluator = new DefaultSessionStorageEvaluator();
    evaluator.setSessionStorageEnabled(false);
    return evaluator;
  }

  @Bean
  @ConditionalOnMissingBean
  protected SubjectFactory subjectFactory() {
    return new StatelessDefaultSubjectFactory();
  }

  @Bean
  @ConditionalOnMissingBean
  protected SessionFactory sessionFactory() {
    return new SimpleSessionFactory();
  }

  @Bean
  @ConditionalOnMissingBean
  protected SessionDAO sessionDAO() {
    return new MemorySessionDAO();
  }

  @Bean
  @ConditionalOnMissingBean
  protected SessionManager sessionManager() {
    DefaultSessionManager sessionManager = new DefaultSessionManager();
    sessionManager.setSessionDAO(sessionDAO());
    sessionManager.setSessionFactory(sessionFactory());
    sessionManager.setDeleteInvalidSessions(sessionManagerDeleteInvalidSessions);
    // 关闭session定时检查，通过setSessionValidationSchedulerEnabled禁用掉会话调度器
    sessionManager.setSessionValidationSchedulerEnabled(false);
    return sessionManager;
  }

  @Bean
  @ConditionalOnMissingBean
  protected SessionsSecurityManager securityManager(List<Realm> realms) {
    SessionsSecurityManager securityManager = createSecurityManager();
    securityManager.setAuthenticator(authenticator());
    securityManager.setAuthorizer(authorizer());
    securityManager.setRealms(realms);
    securityManager.setSessionManager(sessionManager());
    securityManager.setEventBus(eventBus);

    if (cacheManager != null) {
      securityManager.setCacheManager(cacheManager);
    }

    return securityManager;
  }

  @Bean
  @ConditionalOnResource(resources = "classpath:shiro.ini")
  protected Realm iniClasspathRealm() {
    return iniRealmFromLocation("classpath:shiro.ini");
  }

  @Bean
  @ConditionalOnResource(resources = "classpath:META-INF/shiro.ini")
  protected Realm iniMetaInfClasspathRealm() {
    Ini ini = Ini.fromResourcePath("classpath:META-INF/shiro.ini");
    return new IniRealm(ini);
  }

  // @Bean
  @ConditionalOnMissingBean(Realm.class)
  protected Realm missingRealm() {
    throw new NoRealmBeanConfiguredException();
  }

  protected SessionsSecurityManager createSecurityManager() {
    DefaultSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setAuthenticator(authenticator());
    securityManager.setAuthorizer(authorizer());
    securityManager.setRealms(realms);
    securityManager.setSessionManager(sessionManager());

    securityManager.setSubjectDAO(subjectDAO());
    securityManager.setSubjectFactory(subjectFactory());

    RememberMeManager rememberMeManager = rememberMeManager();
    if (rememberMeManager != null) {
      securityManager.setRememberMeManager(rememberMeManager);
    }

    if (cacheManager != null) {
      securityManager.setCacheManager(cacheManager);
    }

    SecurityUtils.setSecurityManager(securityManager);
    return securityManager;
  }

  protected RememberMeManager rememberMeManager() {
    return null;
  }

  private Realm iniRealmFromLocation(String iniLocation) {
    Ini ini = Ini.fromResourcePath(iniLocation);
    return new IniRealm(ini);
  }
}
